package com.alex.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;

import java.util.concurrent.CountDownLatch;

/**
 * 基础测试类：提供开启zookeeper连接和关闭连接
 */
@Slf4j
public class BaseTest {

    /**
     * zookeeper连接
     */
    protected ZooKeeper zooKeeper;

    protected static final String PATH = "/imooc";

    @Before
    public void before() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        // zookeeper创建连接是异步的
        // sessionTimeout:session等待时间, 单位是毫秒
        // watch响应事件触发器
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 30000, watchedEvent -> {
            log.info("event: {}", watchedEvent);
            if (Watcher.Event.KeeperState.SyncConnected == watchedEvent.getState()) {
                log.info("Connection...");
                latch.countDown();
            }

            if (Watcher.Event.KeeperState.Closed == watchedEvent.getState()) {
                log.info("Closed...");
            }
        });

        latch.await();
    }

    @After
    public void after() throws Exception {
        log.info("close.....");
        zooKeeper.close();
    }
}
